//
//  IWeighMyselfAppDelegate.m
//  IWeighMyself
//
//  Created by Francisco Gindre on 7/28/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "IWeighMyselfAppDelegate.h"
#import "RootViewController.h"
#import "Language.h"

@implementation IWeighMyselfAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize plistXML, plistPath, plistFileName, plistFileNameWithExtension;
@synthesize dateFormatter;
@synthesize databaseName;
@synthesize databasePath;
#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
	// Setup some globals
	databaseName = @"WeightDatabase.sql";
	
	// Get the path to the documents directory and append the databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
	
	// Execute the "checkAndCreateDatabase" function
	[self checkAndCreateDatabase];
	
	
	// set the userdate file name
	self.plistFileName=@"UserData";
	
	// Contains the user data filename with the plist extension
	self.plistFileNameWithExtension=[self.plistFileName stringByAppendingString:@".plist"];
	
	//the root path where the user data property list is located
	NSString *basePath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	
	//create full path for accessing the user data property list
	
	self.plistPath = [basePath stringByAppendingPathComponent:self.plistFileNameWithExtension]; 
	
	/*
	 if it's the first time the user runs the app, and no profile is found, create an empty
	 NSMutableDictionary to store the configuration, otherwise load the values from the file
	 */
	
	if (![self isUserDataFilePresent]){
		self.plistXML = [NSMutableDictionary dictionaryWithCapacity:4];
	
	
	} else {
		[self loadUserDataFromPlist];
	}
	
	/*
	 create the date formatter used throughout the app
	 */
	
	self.dateFormatter = [[NSDateFormatter alloc] init];
	
	// set to new behavior
	
	[self.dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
	
	[self.dateFormatter setDoesRelativeDateFormatting:YES];
	
	
	// Add the navigation controller's view to the window and display.
	
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}

#pragma mark -
#pragma mark User Data plist management



/*
 determines whether there is an existing bundle to load existing values or default ones
 */

-(BOOL) isFirstTimeSetup {
	
	if (self.plistXML==nil) {
		return YES;
	}
	return ([self.plistXML count]==0)?YES:NO;
	
}
/*
 determines if the application was set up for the first time or not
 based on the size of the dictionary that contains the configuration
 parameters
 */			
			
-(BOOL)isUserDataFilePresent {
	return [[NSFileManager defaultManager] fileExistsAtPath:plistPath];
	
	
}
-(void) loadUserDataFromPlist {
	
	
	NSString *errorDesc = nil;
	
	NSPropertyListFormat format;
	
	
	if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
		
		plistPath = [[NSBundle mainBundle] pathForResource:self.plistFileName ofType:@"plist"];
		
	}
	
	// get the data from the documents bundle (see didFinishLaunchingWithOptions) 
	
	NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
	
    plistXML = (NSMutableDictionary *)[NSPropertyListSerialization
                                                      
                                                      propertyListFromData:plistData
                                                      
                                                      mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                                      
                                                      format:&format
                                                      
                                                      errorDescription:&errorDesc];
	
	
    
	[plistXML retain];
    // check if something went wrong
	if (!plistXML){
		NSLog(@"error loading plist %@",errorDesc);
	}
	    	
	
}


/* 
 checks if kilos is the default weight unit
 */

-(BOOL)isKilosWeightSelectedUnit {
	
	NSString *unit = (NSString*)[self.plistXML objectForKey:@"WeightUnit"];
	
//NSLog(@"selected unit is %@", unit);
	
	//NSLog(@" return value of comparison is %d",([unit localizedCompare:NSLocalizedString(@"WeightUnitKilos",@"")]==NSOrderedSame));
	
	return ([unit localizedCompare:NSLocalizedString(@"WeightUnitKilos",@"")]==NSOrderedSame);
	
	
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}



- (void)dealloc {
	[navigationController release];
	[window release];
	[super dealloc];
}

#pragma mark -
#pragma mark Database handling methods

-(void) checkAndCreateDatabase{
	// Check if the SQL database has already been saved to the users phone, if not then copy it over
	BOOL success;
	
	// Create a FileManager object, we will use this to check the status
	// of the database and to copy it over if required
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	// Check if the database has already been created in the users filesystem
	success = [fileManager fileExistsAtPath:databasePath];
	
	// If the database already exists then return without doing anything
	if(success) return;
	
	// If not then proceed to copy the database from the application to the users filesystem
	
	// Get the path to the database in the application package
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	// Copy the database from the package to the users filesystem
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
	
	[fileManager release];
}


@end

